
Ext.ComboBoxTree = function(){
	this.treeId = Ext.id()+'-tree';
	this.maxHeight = arguments[0].maxHeight || arguments[0].height || this.maxHeight;
	this.tpl = new Ext.Template('<tpl for="."><div style="height:' + this.maxHeight + 'px"><div id="'+this.treeId+'"></div></div></tpl>');
	this.store = new Ext.data.SimpleStore({fields:[],data:[[]]});
	this.selectedClass = '';
	this.mode = 'local';
	this.triggerAction = 'all';
	this.onSelect = Ext.emptyFn;
	this.onViewClick = Ext.emptyFn;
	this.assertValue=Ext.emptyFn;//添加后，下拉框的选择的值不会丢失
	this.editable = false;
	
	//all:所有结点都可选中
	//exceptRoot：除根结点，其它结点都可选
	//folder:只有目录（非叶子和非根结点）可选
	//leaf：只有叶子结点可选
	this.selectNodeModel = arguments[0].selectNodeModel || 'exceptRoot';
	Ext.ComboBoxTree.superclass.constructor.apply(this, arguments);
}

Ext.extend(Ext.ComboBoxTree,Ext.form.ComboBox, {
	treeoption : "",
	treecond:"",
	textfocus :false,
	editor : false,
	oldText : "",
	ddevent: true,
	expand : function(){
		Ext.ComboBoxTree.superclass.expand.call(this);
		if(!this.tree.rendered){
			this.tree.height = this.maxHeight;
			this.tree.border=false;
			this.tree.autoScroll=true;
			this.tree.enableDD=true;
			this.tree.ddAppendOnly=false;
			this.tree.ddScroll=true;
			
			var combox = this;
	        if(this.tree.xtype){
				this.tree = Ext.ComponentMgr.create(this.tree, this.tree.xtype);
			}
			this.tree.render(this.treeId);
			/**
			this.tree.on('contextmenu',function(node,event){
				combox.textfocus=true;
				node.select();
				var nodemenu=new Ext.menu.Menu({  
                      items:[  
                             {text:'添加',iconCls:'buttonAdd',scope:this,handler:function(){
                                	combox.addNode();
                                }},  
                               {text:'修改',iconCls:'buttonUp',scope:this,handler:function(){
                                	combox.updataNode();
                                }},  
                              {text:'删除',iconCls:'buttonDel',scope:this,handler:function(){
                              		var node = combox.tree.getSelectionModel().getSelectedNode();
                              		if(confirm('你是否确定删除此记录吗?')){
                              			combox.delectNode(node);
                              		}
                              }}  
                            ] , 
	              		hide : function(deep){
					        combox.textfocus=false;
					        if(this.el && this.isVisible()){
					            this.fireEvent("beforehide", this);
					            if(this.activeItem){
					                this.activeItem.deactivate();
					                this.activeItem = null;
					            }
					            this.el.hide();
					            this.hidden = true;
					            this.fireEvent("hide", this);
					        }
					        if(deep === true && this.parentMenu){
					            this.parentMenu.hide(true);
					        }
					    },
					    onMouseOut : function(e){
					        var t;
					        combox.textfocus=true;
					        if(t = this.findTargetItem(e)){
					            if(t == this.activeItem && t.shouldDeactivate(e)){
					                this.activeItem.deactivate();
					                delete this.activeItem;
					            }
					        }
					        this.over = false;
					        this.fireEvent("mouseout", this, e, t);
				    }
                 });  
				event.preventDefault();
				nodemenu.showAt(event.getXY());
			}); 
			*/
			this.filter = new Ext.tree.TreeFilter(this.tree, {
				clearBlank: true,
				autoClear: true
			});
			/**
			this.tree.on('beforenodedrop',function(dropEvent){
				var point = dropEvent.point;
				var curText = dropEvent.dropNode.text;
	        	var targetText = dropEvent.target.text;
	        	
				var dropNode = dropEvent.dropNode;
	        	var targetNode = dropEvent.target;	
	        	var curParentText = dropNode.parentNode.text;      
		      	dropEvent.preventDefault = true;
		      	dropEvent.stopPropagation = true;  
		      	if(!this.ddevent) dropEvent.cancel=true;

      	  		if (point == 'append') {
      	  			if(curParentText == targetText) return;
                } else if (point == 'above') {
                	targetNode = targetNode.parentNode;
		        	targetText = targetNode.text; 
                	if(curParentText == targetText) return;
                } else if (point == 'below') {
                	targetNode = targetNode.parentNode;
		        	targetText = targetNode.text; 
                	if(curParentText == targetText) return;
                }
                
                var cNodes = targetNode.childNodes;
				for(var v=0;v<cNodes.length;v++){
					if(cNodes[v].text == curText) {
						alert(targetText + "里已经存在【" + curText + "】");
						dropEvent.cancel=true;
						return;
					}
				}
				
                if(confirm('你是否确定将【' + curText + '】追加到【' + targetText + '】里面！')){
               		dropEvent.cancel=false;	
               		this.ddevent = false;
               		combox.nodeDropSave(dropNode,targetNode);	
                }else{
                	dropEvent.cancel=true;
                }
                
		    },this);*/
			
		     this.treeEditor = new Ext.tree.TreeEditor(
	            this.tree,
	            {allowBlank: true,
	             listeners : {
				    'focus': function(){
				      	combox.textfocus = true;
				    }
				 }}
	         );
							
		     this.treeEditor.on("beforestartedit", function(treeEditor){
		     	if(combox.editor){
		     		combox.editor = false;
		     		return true;
		     	}else{
		     		return false;
		     	}
	         });
	         
	         this.tree.loader.on("beforeload", function(treeLoader, node) {	
			   	  //var text = combox.getNodeCond(node);
			   	  var level = node.getDepth()+1;
			   	  treeLoader.baseParams.level = level;
			      treeLoader.baseParams.parentId = node.attributes.id;
				  treeLoader.baseParams.checked = "false";   
		     }); 	
	         
	         var climetree = {};
         	 climetree["区域"] = "";
			 climetree["盆地"] = "";
			 climetree["坳陷"] = "";
			 climetree["凹陷"] = "";
	         this.tree.on('dblclick',function(node){
	        	var lev=node.attributes.slevel;
	        	//if(lev!=2) return;
	        	if(Ext.getCmp("iformpanel")){
	        		var oobj={};
	        		if(node.parentNode){
	        			var parText=node.parentNode.text;
	        			oobj["所属油田"]=parText;
	        		}
		        	var form = Ext.getCmp("iformpanel");
					var record = new Ext.data.Record(oobj);
					form.setValues(record); 
					combox.setValue(node,true);
				}else{
					grid.getSelectionModel().getSelected().set("所属区块编码",node.id);
					var mynode = {};
					mynode.id = node.text;
					mynode.text = node.text;
					combox.setValue(mynode,true);
				}
	        	var isRoot = (node == combox.tree.getRootNode());
	        	var selModel = combox.selectNodeModel;
	        	var isLeaf = node.isLeaf();
	        	if(isRoot && selModel != 'all'){
	        		return;
	        	}else if(selModel=='folder' && isLeaf){
	        		return;
	        	}else if(selModel=='leaf' && !isLeaf){
	        		return;
	        	}
	        	combox.collapse();
	        });
	        
			var root = this.tree.getRootNode();
			if(!root.isLoaded())
				root.reload();
				
			this.treeEditor.on("complete", function(treeEditor){
				combox.textfocus = false;
				var node = this.tree.getSelectionModel().getSelectedNode();
				var newText = treeEditor.editNode.text;
				if(!newText) treeEditor.editNode.setText("其它");
				if(newText==combox.oldText && combox.treeoption=="mod") return;
				if(combox.treeoption=="mod") {
					if(confirm('油田特征也相应改变是否保存！')){
	                	combox.saveTreeNode(node);
	                }else{
	                	treeEditor.editNode.setText(combox.oldText);
	                }
				}else{
					combox.saveTreeNode(node);
				}
	        });
		}
    },
    
    setValue : function(node){
        var text = node.text;
        this.lastSelectionText = text;
        if(this.hiddenField){
            this.hiddenField.value = node.id;
        }
        Ext.form.ComboBox.superclass.setValue.call(this, text);
        this.value = node.id;
    },
    
    getValue : function(){
    	return typeof this.value != 'undefined' ? this.value : '';
    },
    
    nodeDropSave : function (dropNode,target){
    	var tree = this.tree;
  		var params = {};
    	var flds = [];
    	var data = [];
    	var cond = this.getNodeCond(dropNode);
    	var kind = pageparam.treebusiname;
    	if(dropNode.getDepth() > (target.getDepth() + 1)) {
    		
			flds = ["区域","盆地","坳陷","凹陷"];
			var idx = dropNode.getDepth() - 1;
			var field = "";
			for(var k=idx;k<flds.length;k++){
				if(field) field += ",";
				field += flds[k];
			}
			
			var fldss = [field,0,0];
			var busiobj = {};
			busiobj.tbname = kind;
			busiobj.flds = fldss;	
			busiobj.cond = cond;
			busiobj.order = "data_order";
			var row = window.htmlevent("executeQueryOrder",busiobj,false,"/xbsis/server/base/busilist.jsp");
			this.delectNode(dropNode);
			this.ddevent = true;
			
			var year = new Date().getYear();
			var month = new Date().getMonth() + 1;
			var day = new Date().getDay();
			
			params.option = "ins";
		    params.valid = "";
		    params.bname = kind;
		    params.cond = "";
			flds = ["data_id","data_wrap","data_kind","data_flag","data_otherflag","data_state",
						"data_year","data_month","data_day","data_useflag","data_delflag","区域","盆地","坳陷","凹陷"]; 

			var tnodes = getAllParentNodes(target);	
			for(var i=0;i<tnodes.length;i++){
				var n = tnodes[i];
				if(n.getDepth()==0) continue;
				data.push(n.text);
			}			
						
			params.flds = Ext.util.JSON.encode(flds);
			for(var j=0;j<row.length;j++){
				var insdataid = autoServer.GuidString;
				var rowdata = 	data.concat(row[j]);
				if(rowdata.length==1)rowdata = rowdata.concat(["","",""]);
				if(rowdata.length==2)rowdata = rowdata.concat(["",""]);
				if(rowdata.length==3)rowdata = rowdata.concat([""]);
				var datas = [insdataid,"1",kind,"xbsis",kind,"1",year,month,day,"1","0"];
				rowdata = datas.concat(rowdata);
				params.data = Ext.util.JSON.encode(rowdata);
				Ext.Ajax.request({
   	    			url:"/xbsis/server/base/ComboBoxTree_Ext.jsp" ,
   				 	success:function(response){
   				 		target.reload();
     				 }, 
     				params:params
		     	}) ;
			}
    	}else{
    		var allnodes = getAllParentNodes(target);    
	        for(var i=0;i<allnodes.length;i++){ 
				var n = allnodes[i];
				var n_flds = n.id;
				var n_data = n.text;
				n_data = n_data.trim();
				var idx = n_flds.indexOf("_");
		    	if(idx==-1) continue;
		    	n_flds = n_flds.substring(0,idx);
		    	flds[flds.length] = n_flds;
				data[data.length] = n_data;
		    } 
		    params.option = "mod";
		    params.valid = "";
		    params.bname = pageparam.treebusiname;
		    params.cond = cond;
		    params.flds = Ext.util.JSON.encode(flds);
		    params.data = Ext.util.JSON.encode(data);
	   	    Ext.Ajax.request({
	   	    			url:"/xbsis/server/base/ComboBoxTree_Ext.jsp" ,
	   				 	success:function(response){
	   				 			target.reload();
	     				 	}, 
	     				params:params
	     	}) ;
	     	
	     	if(!dropNode.nextSibling && !dropNode.previousSibling){
				var obj = {};
   				var _kind = pageparam.treebusiname;
   				if(dropNode.getDepth()>1){
					var fieldArray = this._fieldArray(dropNode.parentNode,_kind);
		    		var flds = fieldArray.flds;
		    		var data = fieldArray.data;
				    obj.option = "ins";
				    obj.valid = "";
				    obj.bname = _kind;
				    obj.flds = Ext.util.JSON.encode(flds);
				    obj.data = Ext.util.JSON.encode(data);
    				Ext.Ajax.request({url:"/xbsis/server/base/busicard_Array_Ext.jsp" , params:obj}) ;
   				}
   			}
    	}
    },
    
    getNodeCond : function (node){
 		var text = ""; 
 		var allnodes = getAllParentNodes(node)    
        for(var i=0;i<allnodes.length;i++){ 
			var n = allnodes[i];
			var id = n.id;
			var n_text = n.text;
			n_text = n_text.trim();
			var idx = id.indexOf("_");
	    	if(idx==-1) continue;
	    	id = id.substring(0,idx);
			if(text) text += " and ";
			text += id + "='" + n_text + "'";
	    } 
   	    return text;
    },
    
    collapse : function(){
        if(!this.isExpanded()){
            return;
        }
        if(this.textfocus) return;
        this.list.hide();
        Ext.getDoc().un('mousewheel', this.collapseIf, this);
        Ext.getDoc().un('mousedown', this.collapseIf, this);
        this.fireEvent('collapse', this);
    },
    expandTree : function(expand){
    	var tree = this.tree;
    	var node = tree.getSelectionModel().getSelectedNode();
    	if(!node) {
      		alert("你尚未选定一个节点") ;
      	}else{
      		if(node.isLeaf()) alert("对不起！当前为叶子节点！");
	    	if(expand) {
	    		if(node.isExpanded()){
			    	alert("当前节点已经展开");
		            return;
		        }
	    		tree.body.mask('数据加载中……', 'x-mask-loading');
	    		node.expand(true,true,function(){ 
					tree.body.unmask();
				});
	    	}else{
			    if(!node.isExpanded()){
			    	alert("当前节点已经合并");
		            return;
		        }
		        node.collapse(true);
	    	}
    	}
    },
    
    delectNode : function(node){
        if(!node) {
      		alert("你尚未选定一个节点") ;
      	}else{
      		if(!node.parentNode) return;
    		try{
				var bname = pageparam.treebusiname;
				var cond = this.getNodeCond(node);
				var _params = {
					bname : bname,
					cond : cond,
					option : "del"
				}
				Ext.Ajax.request({url:"/xbsis/server/base/busicard_Array_Ext.jsp" , params:_params}) ;
				if(!node.nextSibling && !node.previousSibling){
					var params = {};
    				var _kind = pageparam.treebusiname;
    				if(node.getDepth()>1){
						var fieldArray = this._fieldArray(node.parentNode,_kind);
			    		var flds = fieldArray.flds;
			    		var data = fieldArray.data;
					    params.option = "ins";
					    params.valid = "";
					    params.bname = _kind;
					    params.flds = Ext.util.JSON.encode(flds);
					    params.data = Ext.util.JSON.encode(data);
     					Ext.Ajax.request({url:"/xbsis/server/base/busicard_Array_Ext.jsp" , params:params}) ;
    				}
    			}
	    		node.remove();
	    		this.textfocus=false;
			}catch(_err){
				alert(_err.description) ;
			}
      	}
    },
    updataNode : function(){
    	var selectedNode = this.tree.getSelectionModel().getSelectedNode();// 得到选中的节点
    	if(!selectedNode) {
      		alert("你尚未选定一个节点") ;
      	}else{
      		this.treeoption = "mod";
      		this.oldText = selectedNode.text;
      		this.editor = true;
      		this.treecond = this.getNodeCond(selectedNode);
      		this.treeEditor.editNode = selectedNode;
  			this.treeEditor.startEdit(selectedNode.ui.textNode);
      	}
    },
    
 	addNode : function (){
	    var tree = this.tree;
		var treeEditor = this.treeEditor;
	    var selectedNode = tree.getSelectionModel().getSelectedNode();
	    if(!selectedNode) {
      		alert("你尚未选定一个节点") ;
      	}else{
		    if(selectedNode.isLeaf()) return;
		    
		    var id = selectedNode.id;
		    id = id.substring(0,id.indexOf('_'));
		    var leaf = false;
		    var expandable = true;
		    if(id=="坳陷"){ leaf = true;expandable=false;}
		    
		   	if (!id){id = "区域";}
		   	else if (id == "区域"){id = "盆地";}
		   	else if (id == "盆地"){id = "坳陷";}
		   	else if (id == "坳陷"){id = "凹陷";}
		    id = id + "_" +autoServer.GuidString
	    
      		if (selectedNode.isLeaf()) {
	   			selectedNode.leaf = false;
		  	}
			this.treeoption = "ins";
			this.editor = true;
		  	selectedNode.expand(false, true, function() {
		 		var newNode = selectedNode.insertBefore(new Ext.tree.TreeNode({
		    		text : '新建节点',
		    		leaf: leaf,
		    		expandable: expandable,
		    		id : id
		   		}),selectedNode.firstChild);
			    		
			  	tree.getSelectionModel().select(newNode);
			  		setTimeout(function() {
			        	treeEditor.editNode = newNode;
			        	treeEditor.startEdit(newNode.ui.textNode);
			        }, 10);
		  	});
      	}
	  	
    },
    
    saveTreeNode : function(selectedNode){
    	var params = {};
    	var flds = [];
    	var data = [];
    	var _kind = pageparam.treebusiname;
    	var option = this.treeoption;
    	var valid = this.getNodeCond(selectedNode);
    	if(!selectedNode.nextSibling && selectedNode.getDepth()>1) {
    		option = "mod";
    		this.treecond = this.getNodeCond(selectedNode.parentNode);
    	}
    	if(option == "ins"){
    		var fieldArray = this._fieldArray(selectedNode,_kind);
    		flds = fieldArray.flds;
    		data = fieldArray.data;
    	}else{
    		params.cond = this.treecond;
	    	var n_flds = selectedNode.id;
	    	flds[flds.length] = n_flds.substring(0,n_flds.indexOf('_'));
	    	data[data.length] = selectedNode.text;
    	}
    	
	    params.option = option;
	    params.valid = valid;
	    params.bname = _kind;
	    params.flds = Ext.util.JSON.encode(flds);
	    params.data = Ext.util.JSON.encode(data);
	    var tree = this.tree;
	    tree.body.mask('数据保存中……', 'x-mask-loading');
	    Ext.Ajax.request({url:"/xbsis/server/base/ComboBoxTree_Ext.jsp" ,
	    				 success:function(response){
	    				 	var data = response.responseText;
           					data = eval("(" + data + ")");
           					data = data.success;
           					var field = selectedNode.id;
           					var parentNode = selectedNode.parentNode;
           					field = field.substring(0,field.indexOf("_"));
           					if(data == "valfalse") alert("保存失败！当前节点" +field + "名称为【 " + selectedNode.text.trim() + " 】的已经存在！");
	    				 	if(option == "ins") {if(data == "valfalse") parentNode.reload()}
	    				 	else{
	    				 		if(!selectedNode.isLeaf()) {
	    				 			if(data == "valfalse") parentNode.reload();
	    				 			else{}
	    				 		}else{
	    				 			if(data == "valfalse") parentNode.reload();
	    				 		}
	    				 	}
							tree.body.unmask();
	      				 }, 
	      				 params:params
	      		}) ;
    },
    
    _fieldArray : function(node,_kind){
    	var params = {};
    	var insdataid = autoServer.GuidString;
		var year = new Date().getYear();
		var month = new Date().getMonth() + 1;
		var day = new Date().getDay();
		
		var flds = ["data_id","data_wrap","data_kind","data_flag","data_otherflag","data_state",
					"data_year","data_month","data_day","data_useflag","data_delflag"];
		var data = [insdataid,"1",_kind,"xbsis",_kind,"1",year,month,day,"1","0"];
		
		var allnodes = getAllParentNodes(node);    
        for(var i=0;i<allnodes.length;i++){ 
			var n = allnodes[i];
			var n_flds = n.id;
			var n_data = n.text;
			n_data = n_data.trim();
			var idx = n_flds.indexOf("_");
	    	if(idx==-1) continue;
	    	n_flds = n_flds.substring(0,idx);
	    	flds[flds.length] = n_flds;
	    	data[data.length] = n_data;
	    }
	    params.flds = flds;
	    params.data = data;
	    return params;
    },
    
    
	hiddenPkgs:[],
	filterTree:function(e){
	var tree = this.tree;
		
		var combox = this;
		var tree = combox.tree;
		
		tree.expandAll();
		
		var text = e;
		
		Ext.each(combox.hiddenPkgs, function(n){
			n.ui.show();
		});
		if(!text){
			this.filter.clear();
			return;
		}
		
		var re = new RegExp('^' + Ext.escapeRe(text), 'i');
		this.filter.filterBy(function(n){
			return !n.attributes.isClass || re.test(n.text);
		});
		
		combox.hiddenPkgs = [];
		
		tree.getRootNode().cascade(function(n){
			if(!n.attributes.isClass && n.ui.ctNode.offsetHeight < 3){
				n.ui.hide();
				combox.hiddenPkgs.push(n);
			}
		});
	
	}
});

	Ext.reg('combotree', Ext.ComboBoxTree);
function getAllParentNodes(node)
{ 
	var parentNodes=[]; 
	if(node){
		parentNodes.push(node); 
		if(node.parentNode){ 
			parentNodes = parentNodes.concat(getAllParentNodes(node.parentNode)); 
		} 
	}
	return parentNodes; 
}; 

